package com.haorui.lygyd.authority.jwt;

import com.haorui.base.core.dto.AuthDto;
import com.haorui.base.core.exception.IntercetorException;
import com.haorui.lygyd.authority.dto.AuthMember;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2017/8/10
 * 时间: 15:37
 * 功能：JWT Token 工具类
 */
@Component
public class JwtTokenUtil {
    private static final String CLAIM_KEY_USERNAME = "username";
    private static final String CLAIM_KEY_ID = "id";
    private static final String CLAIM_KEY_TYPE = "type";
    private static final String CLAIM_KEY_ORGID = "orgid";
    private static final String CLAIM_KEY_OPENID="openid";

    private static final String CLAIM_KEY_CREATED = "created";

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 生成后台account登陆用户token
     * @param authDto
     * @return
     */
    public String generateAccountToken(AuthDto authDto) {
        Map<String, Object> claims = new HashMap<String,Object>();
        claims.put(CLAIM_KEY_ID,authDto.getId());
        claims.put(CLAIM_KEY_USERNAME, authDto.getUserName());
        claims.put(CLAIM_KEY_TYPE,authDto.getType());
        claims.put(CLAIM_KEY_ORGID,authDto.getOrgid());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }
    /**
     * 生成后台account登陆用户token
     * @param authDto
     * @return
     */
    public String generateMemberToken(AuthMember authDto) {
        Map<String, Object> claims = new HashMap<String,Object>();
        claims.put(CLAIM_KEY_ID,authDto.getId());
        claims.put(CLAIM_KEY_USERNAME, authDto.getUserName());
        claims.put(CLAIM_KEY_TYPE,authDto.getType());
        claims.put(CLAIM_KEY_ORGID,authDto.getOrgid());
        claims.put(CLAIM_KEY_OPENID,authDto.getOpenId());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }


    /**
     * 从token 中获取id
     * @param authToken
     * @return
     */
    public String getId(String authToken){
        try {
            Claims claims=getClaimsFromToken(authToken);
            return (String)claims.get(CLAIM_KEY_ID);
        }catch (Exception e){
            throw new JwtException("获取"+CLAIM_KEY_ID+"失败！",e);
        }
    }

    /**
     * 获取OpenId
     * @param authToken
     * @return
     */
    public String getOpenId(String authToken){
        try {
            Claims claims=getClaimsFromToken(authToken);
            return (String)claims.get(CLAIM_KEY_OPENID);
        }catch (Exception e){
            throw new JwtException("获取"+CLAIM_KEY_OPENID+"失败！",e);
        }
    }

    /**
     * 从token 中获取username
     * @param authToken
     * @return
     */
    public String getAccountUserName(String authToken){
        try {
            Claims claims=getClaimsFromToken(authToken);
            return (String)claims.get(CLAIM_KEY_USERNAME);
        }catch (Exception e){
            throw new JwtException("获取"+CLAIM_KEY_USERNAME+"失败！",e);
        }
    }

    /**
     * 从token 中获取 账户类型
     * @param authToken
     * @return
     */
    public String getType(String authToken){
        try {
            Claims claims=getClaimsFromToken(authToken);
            return (String)claims.get(CLAIM_KEY_TYPE);
        }catch (Exception e){
            throw new JwtException("获取"+CLAIM_KEY_TYPE+"失败！",e);
        }
    }

    public String getUsernameFromToken(String token) throws IntercetorException {
        String username;
        try {
            final Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            throw new IntercetorException("getUsernameFromToken method error!\n"+e.getMessage());
        }
        return username;
    }

    public Date getCreatedDateFromToken(String token) throws IntercetorException {
        Date created;
        try {
            final Claims claims = getClaimsFromToken(token);
            created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
        } catch (Exception e) {
            throw new IntercetorException("getCreatedDateFromToken method error!\n"+e.getMessage());
        }
        return created;
    }

    public Date getExpirationDateFromToken(String token) throws IntercetorException {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            throw new IntercetorException("getExpirationDateFromToken method error!\n"+e.getMessage());
        }
        return expiration;
    }

    private Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    public Boolean isTokenExpired(String token) throws IntercetorException {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
        return (lastPasswordReset != null && created.before(lastPasswordReset));
    }



   public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) throws IntercetorException {
        final Date created = getCreatedDateFromToken(token);
        return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
                && !isTokenExpired(token);
    }

    public String refreshToken(String token) {
        String refreshedToken;
        try {
            final Claims claims = getClaimsFromToken(token);
            claims.put(CLAIM_KEY_CREATED, new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    public Boolean validateToken(String token,String accountName) throws IntercetorException {
        final String username = getUsernameFromToken(token);
        return (
                username.equals(accountName)
                        && !isTokenExpired(token));
    }
}
